<template>
  <a-card>
    <div class="outer_box"  v-if="previewVisible">
      <previewPicture :isEdit="false"  @cancel="previewVisible = false" :fileList="previewFileList" :fileNum="previewNum"></previewPicture>
    </div>
    <a-tabs defaultActiveKey="1" style="margin-top: 5px;">
      <a-tab-pane :tab="title" key="1">
        <a-form :form="form">
      <a-form-item v-if="flag==='file' || flag==='all'">
        <a-upload
          v-show="!disabled"
          name="file"
          :action="uploadAction"
          :headers="headers"
          :data="{'parenPath':'schedule','uploadType':'5'}"
          :showUploadList="false"
          :multiple="true"
          @change="handleChange"
        >
          <a-button>
            <a-icon type="upload" />{{buttonTitle}}
          </a-button>
        </a-upload>
      </a-form-item>
      <div v-if="flag==='file' || flag==='all'">
        <a-list itemLayout="horizontal" :dataSource="sysFileList">
          <a-list-item slot="renderItem" slot-scope="item">
            <a v-if="!disabled" @click="deleteFile(item.fileId)" slot="actions">删除</a>
            <a-list-item-meta description>
              <a
                target="_blank"
                style="color:#1890FF"
                slot="title"
                :href="buildFilePath(item.filePath)"
              >{{item.originalName}}</a>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
      </div>


      <a-form-item v-if="flag=='img' || flag==='all'">
        <a-upload
          @preview="handlePreview"
          :disabled="disabled"
          list-type="picture-card"
          :multiple="true"
          :action="uploadAction"
          :headers="headers"
          :file-list="imageList"
          :before-upload="uploadImage"
          :data="{'parenPath':'schedule','uploadType':'0'}"
          :remove="handleRemove"
        >
          <div v-show="!disabled">
            <a-icon type="plus" />
            <div class="ant-upload-text">
              {{buttonTitle}}
            </div>
          </div>
        </a-upload>
      </a-form-item>


    </a-form>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script>
  import Vue from 'vue'
  import { SOURCE_NAME } from '@/store/mutation-types'
  import { REDIS_INDEX } from '@/store/mutation-types'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import {putAction,postAction,getAction} from '@/api/manage';
  import PreviewPicture from '@/components/tools/PreviewPicture'
  import axios from 'axios'
  export default {
    components:{
      PreviewPicture
    },
    name: 'FileUploadFlowModal',
    props: {
      tableId: String
    },
    data(){
      return{
        flag:'file',
        previewNum:0,
        previewFileList:{},
        previewVisible:false,
        disabled:false,
        title:'审核附件',
        buttonTitle:'上传',
        //图片上传插件请求头部
        headers:{},
        form: this.$form.createForm(this),
        sysFileList: [],
        sysImageList: [],
        imageList:[],
        url: {
          fileUploadImg: window._CONFIG['domianURL'] + '/common/file/uploadImg?parenPath=travel&uploadType=0',
          fileUpload: window._CONFIG['domianURL'] + '/common/file/uploadImg',
          uploadFile: "/expenditure/expenditureOfficeInfo/uploadFileReview",
          queryFileList: "/expenditure/expenditureOfficeInfo/getSysFileListByMainType",
        }
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token,
        "sourceName":Vue.ls.get(SOURCE_NAME),
        "redisIndex":Vue.ls.get(REDIS_INDEX)
      };
    },
    mounted(){
      $('.ant-upload-disabled').remove()
    },
    computed:{
      uploadAction:function(){
        return this.url.fileUpload;
      }
    },
    methods: {
      handleRemove(file){
        console.log(file,"file")
        let index = 0
        console.log(this.imageList,"this.imgList1")
        for (let i = 0; i < this.imageList.length; i++) {
          if(file.uid === this.imageList[i].uid){
            index = i
          }
        }

        console.log(this.sysImageList,"this.sysImageList1")
        this.imageList.splice(index,1)
        this.sysImageList.splice(index,1)
        console.log(this.imageList,"this.imgList2")
        console.log(this.sysImageList,"this.sysImageList2")
        return true
      },
      handlePreview(file){
        this.previewFileList.showList = this.imageList
        this.previewNum = 0
        for (let i = 0; i < this.imageList.length; i++) {
          if(file.uid === this.imageList[i].uid){
            this.previewNum = i
          }
        }
        this.previewVisible = false
        this.previewVisible = true
      },
      buildFilePath(filePath) {
        return window._CONFIG['staticDomainURL'] + '/' + filePath
      },
      //上传完文件，往enclosureList传值，用来展示
      handleChange(info) {
        let result = info.fileList
        if (info.file.status == 'uploading') {

        }else if(info.file.status == 'done'){
          if (info.file.response) {
            let temp = {}
            temp.fileId = new Date().getTime().toString()
            temp.originalName = info.file.response.result.originalName
            temp.fileName = info.file.response.result.fileName.split('.')[1]
            temp.filePath = info.file.response.result.filePath
            temp.fileId = info.file.response.result.id
            this.sysFileList.push(temp)
          }
        }
      },
      uploadImage(file){
        return new Promise((resolve,reject) => {
          let params = new FormData()
          params.append('file', file)
          let config = {
            headers: {
              //添加请求头
              'Content-Type': 'multipart/form-data',
              "sourceName":Vue.ls.get('SOURCE_NAME'),
              "redisIndex":Vue.ls.get('REDIS_INDEX'),
            }
          }
          axios.post(this.url.fileUploadImg, params, config).then(res => {
            if (res.data.success) {
              let temp = {}
              temp.fileId = res.data.result.id
              temp.filePath = res.data.result.filePath
              temp.thumPath = res.data.result.thumPath
              temp.fileName = res.data.result.originalName
              this.sysImageList.push(temp)
              let tmp = {}
              tmp.uid = res.data.result.id
              tmp.name = res.data.result.originalName
              tmp.url = this.buildFilePath(res.data.result.thumPath)
              tmp.originalImage = this.buildFilePath(res.data.result.filePath)
              this.imageList.push(tmp)

              reject(0)

            }else{
              this.$message.warn("上传失败")
              reject(0)
            }
          })
        })
      },

      //删除上传的文件
      deleteFile(fileId) {
        for (let i = 0; i < this.sysFileList.length; i++) {
          if (this.sysFileList[i].fileId == fileId) {
            this.sysFileList.splice(i, 1)
          }
        }
      },
      getData: function(id,flag){
        this.sysFileList = [];
        this.sysImageList=[]
        this.imageList=[]

        if(flag){
          this.flag = flag
        }else{
          this.flag = 'file'
        }

        getAction('/sys/dict/getDictText/upload_file_flow/title').then(res=>{
          if(res.success && res.result){
            this.title = res.result
          }
        })
        getAction('/sys/dict/getDictText/upload_file_flow/buttonTitle').then(res=>{
          if(res.success && res.result){
            this.buttonTitle = res.result
          }
        })
        getAction(this.url.queryFileList,{mainId: id}).then(res => {
          if(res.success){
            this.sysFileList = res.result.review?res.result.review:[]
            this.sysImageList = res.result.reviewImage?res.result.reviewImage:[]
            if(res.result.reviewImage){
              for (let i = 0; i < res.result.reviewImage.length; i++) {
                let data = res.result.reviewImage
                let temp = {}
                temp.uid = data[i].id
                temp.name = data[i].originalName
                temp.url = this.buildFilePath(data[i].thumPath)
                temp.originalImage = this.buildFilePath(data[i].filePath)
                this.imageList.push(temp)
              }
            }
          }else{
            this.$message.error("获取文件列表失败！");
          }
        });
      },
      handleOk: function(){
        return new Promise((resolve, reject) => {
          if ((this.flag==='file' || this.flag==='all' )&&this.sysFileList.length <= 0) {
            this.$message.warn("请上传附件");
            reject(0)
            return false;
          }else if((this.flag==='img' || this.flag==='all' )&&this.sysImageList.length <= 0){
            this.$message.warn("请上传图片附件");
            reject(0)
            return false;
          } else {
            postAction(this.url.uploadFile,
              {
                mainId: this.tableId,
                sysFileList: this.sysFileList,
                sysImageList:this.sysImageList
              }).then((res) => {
              if (res.success) {
                resolve(1)
              } else {
                this.$message.error(res.message);
                reject(0)
                return false;
              }
            });
          }
        })
      },
      handleCancel: function(){
        this.sysFileList = [];
        this.sysImageList=[]
        this.imageList=[]
      },
    }
  }
</script>

<style scoped>

  .outer_box{
    /*width: 200px;*/
    /*height: 200px;*/
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0px;
    top: 0px;
    background: rgba(0,0,0,.5);
    z-index: 50;
    text-align: center;
  }
  .outer_box>div{
    white-space: nowrap;
    display: inline-block;
  }
  .outer_box>div>img{
    width: auto;
    height: auto;
    position: absolute;
  }
</style>